const Koa = require('koa')
const app = new Koa()
// 引入connect
const { connect, initSchemas } = require('./database/init')
const mongoose = require('mongoose')
const bodyParser = require('koa-bodyparser')
// 解决跨域
const cors = require('koa2-cors')
const Router = require('koa-router')

app.use(bodyParser())
app.use(cors())

let user = require('./appApi/user')
let goods = require('./appApi/goods')

// 装载所有子路由
let router = new Router()
router.use('/user', user.routes())
router.use('/goods', goods.routes())

// 加载路由中间件
app.use(router.routes())
app.use(router.allowedMethods())


// 立即执行函数
;(async () => {
	await connect()
	initSchemas()
	/*
	const User = mongoose.model('User')
	let oneUser = new User({
		userName: 'lenglu',
		password: 'z123456'
	})
	oneUser.save().then((a, b) => {
		console.log(a)
		console.log(b)
		console.log('插入成功。')
	})
	*/
})()

// logger
app.use(async (ctx, next) => {
	const start = Date.now()
	await next()
	const ms = Date.now() - start
	console.log(`${ctx.method} ${ctx.url} - ${ms}`)
})

app.use(async(ctx) => {
	ctx.body = '<h1>Hello Koa2.</h1>'
})

app.on('error', (err, ctx) => {
	log.error('server error', err, ctx)
})

app.listen(3000, () => {
	console.log('[Server] starting at port 3000')
})